package com.security.manage.user.controller;

import com.security.manage.user.dto.ComboDto;
import com.security.manage.user.dto.TaskResp;
import com.security.manage.user.model.*;
import com.security.manage.user.repository.TaskRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class TaskController {

    @Resource
    private TaskRepository taskRepository;

    @PostMapping("/update/task/status")
    public ResData taskInfo(Long taskId){

        if (taskId==null|| taskId==0L){
            return new ResData(0,"参数异常",null);
        }
        Optional<Task> optionalTask = taskRepository.findById(taskId);
        if (optionalTask.isPresent()){
            Task task = optionalTask.get();
            task.setStatus(1);
            task.setUpdateTime(LocalDateTime.now());

            taskRepository.save(task);
            return new ResData(1,"修改成功","");
        }

        return new ResData(0,"任务不存在","");

    }

    @GetMapping("/task/info")
    public ResData taskInfo(@RequestParam("name")String name){

        if (StringUtils.isEmpty(name)){
            return new ResData(0,"参数错误","");
        }
        //ComputerInfo computerInfo = computerInfoRepository.findByName(name);

        //Task task = taskRepository.findByComputerInfoIdAndStatus(computerInfo.getId(),0);
        Map<String,Object> map = new HashMap<>();
        //if (task==null){
            //return new ResData(0,"此计算机没有对应的任务信息","");
        //}

        //map.put("userId",task.getUser().getId());
        //map.put("taskId",task.getId());
        return new ResData(1,"获取成功",map);
    }

    @PostMapping("/task")
    public ResData addTask(@RequestBody Task task,Long userId,Long computerId){

        if (userId==null|| userId==0L || computerId==null || computerId==0L){
            return new ResData(0,"用户不能为空",null);
        }

        if (task.getId()==null){
            task.setCreateTime(LocalDateTime.now());
        }

        User user = new User(userId);
        //ComputerInfo computerInfo = new ComputerInfo(computerId);
        //task.setComputer(computerInfo);
        task.setUser(user);

        taskRepository.save(task);
        return new ResData(1,"成功");
    }

    @GetMapping("/task/{id}")
    public ResData getTask(@PathVariable("id") Long id){
        Optional<Task> role = taskRepository.findById(id);
        return role.map(dept -> new ResData<>(1, "获取成功", dept)).orElseGet(() -> new ResData(0, "获取失败"));
    }

    @GetMapping("task/combo")
    public ResData deptCombo(){
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        List<Task> all = taskRepository.findAll(sort);
        List<ComboDto> comboDtos = new ArrayList<>();
        List<Task> tasks = all.stream().filter(task -> task.getStatus() == 1).collect(Collectors.toList());
        tasks.forEach(t -> comboDtos.add(new ComboDto(t.getId(),t.getTaskName())));
        return new ResData<>(1, "获取成功", comboDtos);
    }

    @GetMapping("/task/list")
    public ResData listTask(@RequestParam(value = "page",defaultValue = "0") Integer page,
                            @RequestParam(value = "size",defaultValue = "10") Integer size){

        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest of = PageRequest.of(page, size, sort);
        Page<Task> pages = taskRepository.findAll(of);

        Map<String,Object> map = new HashMap<>();
        map.put("total",pages.getTotalElements());
        List<Task> collect = pages.get().collect(Collectors.toList());
        List<TaskResp> result = new ArrayList<>();
        for (Task task :collect){
            TaskResp resp = new TaskResp();
            BeanUtils.copyProperties(task,resp);
            //resp.setComputerName(task.getComputer().getName());
            resp.setUserName(task.getUser().getUserName());
            resp.setUserId(task.getUser().getId());
            //resp.setComputerId(task.getComputer().getId());
            result.add(resp);
        }
        map.put("data",result);

        return new ResData<>(1, "获取成功", map);
    }

}
